package uscdb.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import uscdb.pageModel.DataGrid;
import uscdb.pageModel.Json;
import uscdb.pageModel.Logic;
import uscdb.pageModel.PageHelper;
import uscdb.service.LogicServiceI;
import uscdb.util.ConfigUtil;
import uscdb.util.StringUtil.StringUtil;

/**
 * logic 管理控制器
 */
@Controller
@RequestMapping("/logicController")
public class LogicController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(LogicController.class);

	@Autowired
	private LogicServiceI logicService;

	@ResponseBody
	@RequestMapping("/exportLogic")
	public Json exportLogic(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
		String resultString = "导出成功";
		Json json = new Json();
		json.setSuccess(true);
		try {
			// 文件保存目录路径
			String savePath = session.getServletContext().getRealPath("/") + "attached/export/";

			// 增加日期目录，便于归档
			SimpleDateFormat yearDf = new SimpleDateFormat("yyyy");
			SimpleDateFormat monthDf = new SimpleDateFormat("MM");
			SimpleDateFormat dateDf = new SimpleDateFormat("dd");
			Date date = new Date();
			String ymd = yearDf.format(date) + "/" + monthDf.format(date) + "/" + dateDf.format(date) + "/";
			savePath += ymd;
			File dirFile = new File(savePath);
			if (!dirFile.exists()) {
				dirFile.mkdirs();
			}

			// 导出logic压缩文件
			if (logicService.exportLogic(savePath, true)) {
				// 以流的形式下载文件。
				BufferedInputStream fis = new BufferedInputStream(new FileInputStream(savePath + "Logic.zip"));
				byte[] buffer = new byte[fis.available()];
				fis.read(buffer);
				fis.close();
				// 清空response
				response.reset();
				OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
				response.setContentType("application/octet-stream");
				response.setHeader("Content-Disposition", "attachment;filename=Logic.zip");
				toClient.write(buffer);
				toClient.flush();
				toClient.close();
			} else {
				resultString = StringUtil.speakToUser("export");
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			resultString = "The system is broken!";
		}
		json.setMsg(resultString);
		return json;
	}

	@ResponseBody
	@RequestMapping("/importLogic")
	public Json importLogic(HttpServletResponse response, HttpServletRequest request, HttpSession session) {
		Json json = new Json();
		try {
			// 文件保存目录路径
			String savePath = session.getServletContext().getRealPath("/") + "attached/import/";

			// 定义允许上传的文件扩展名
			HashMap<String, String> extMap = new HashMap<String, String>();
			extMap.put("rarFile", ConfigUtil.get("rarFile"));

			long maxSize = Long.parseLong(ConfigUtil.get("maxFileSize")); // 允许上传最大文件大小(字节)

			if (!ServletFileUpload.isMultipartContent(request)) {
				json.setMsg("请选择文件！");
				return json;
			}

			// 检查目录
			File uploadDir = new File(savePath);
			if (!uploadDir.isDirectory()) {
				uploadDir.mkdirs();
			}

			// 检查目录写权限
			if (!uploadDir.canWrite()) {
				json.setMsg("上传目录没有写权限！");
				return json;
			}

			// 增加日期目录，便于归档
			SimpleDateFormat yearDf = new SimpleDateFormat("yyyy");
			SimpleDateFormat monthDf = new SimpleDateFormat("MM");
			SimpleDateFormat dateDf = new SimpleDateFormat("dd");
			Date date = new Date();
			String ymd = yearDf.format(date) + "/" + monthDf.format(date) + "/" + dateDf.format(date) + "/";
			savePath += ymd;
			File dirFile = new File(savePath);
			if (!dirFile.exists()) {
				dirFile.mkdirs();
			}

			if (ServletFileUpload.isMultipartContent(request)) {// 判断表单是否存在enctype="multipart/form-data"
				FileItemFactory factory = new DiskFileItemFactory();
				ServletFileUpload upload = new ServletFileUpload(factory);
				upload.setHeaderEncoding("UTF-8");
				try {
					List<FileItem> items = upload.parseRequest(request);
					// String logicFilePath = "";
					// 上传的文件流
					File uploadedFile = null;
					// 保存表单值的对象，目前是保存 versionname
					Logic logic = new Logic();
					for (FileItem item : items) {
						String fileName = item.getName();
						if (!item.isFormField()) {
							// 检查文件大小
							if (item.getSize() > maxSize) {
								json.setMsg("上传文件大小超过限制！(允许最大[" + maxSize + "]字节，您上传了[" + item.getSize() + "]字节)");
								return json;
							}
							// 检查扩展名
							String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
							if (!Arrays.<String> asList(extMap.get("rarFile").split(",")).contains(fileExt)) {
								json.setMsg(StringUtil.speakToUser("import"));
								return json;
							}

							String newFileName = UUID.randomUUID().toString() + "." + fileExt;
							try {
								uploadedFile = new File(savePath, newFileName);
								item.write(uploadedFile);
							} catch (Exception e) {
								json.setMsg("上传文件失败！");
								return json;
							}
						} else {
							String name = item.getFieldName();
							if ("versionname".equals(name)) {
								String versionname = item.getString();
								logic.setVersionname(versionname);
							}
						}
					}
					// 获取所有信息之后再统一处理
					logicService.importLogic(uploadedFile, logic);
					if (true) {
						json.setMsg("导入logic成功");
						json.setSuccess(true);
					}
				} catch (FileUploadException e) {
					logger.error(e.getMessage(), e);
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			json.setMsg("系统故障，请联系管理员");
		}
		return json;
	}

	/**
	 * 跳转到 logic 管理页面
	 * 
	 * @return
	 */
	@RequestMapping("/manager")
	public String manager(HttpServletRequest request) {
		return "/logic/logic";

	}

	/**
	 * 获取 logic 数据表格
	 * 
	 * @param logic
	 *            页面对象
	 * @param script
	 *            页面对象
	 * @return
	 */
	@RequestMapping("/dataGrid")
	@ResponseBody
	public DataGrid dataGrid(Logic logic, PageHelper ph) {
		return logicService.dataGrid(logic, ph);
	}

	/**
	 * 跳转到添加logic页面
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("/addPage")
	public String addPage(HttpServletRequest request) {
		Logic logic = new Logic();
		logic.setId(UUID.randomUUID().toString());
		request.setAttribute("logic", logic);
		return "/logic/logicAdd";
	}

	/**
	 * 添加logic
	 * 
	 * @return
	 */
	@RequestMapping("/add")
	@ResponseBody
	public Json add(Logic logic) {
		Json json = new Json();
		try {
			logic.setHeat(1L);
			logicService.add(logic);
			json.setSuccess(true);
			json.setMsg("添加成功！");
		} catch (Exception e) {
			logger.error("The error logic is : " + logic.toString());
			logger.error(e.getMessage(), e);
			json.setMsg("系统故障，请联系管理员");
		}
		return json;
	}

	/**
	 * 跳转到logic查看页面
	 * 
	 * @return
	 */
	@RequestMapping("/view")
	public String view(HttpServletRequest request, String id) {
		Logic logic = logicService.get(id);
		logicService.increaseHeat(logic);
		request.setAttribute("logic", logic);
		return "/logic/logicView";
	}

	/**
	 * 跳转到logic修改页面
	 * 
	 * @return
	 */
	@RequestMapping("/editPage")
	public String editPage(HttpServletRequest request, String id) {
		Logic logic = logicService.get(id);
		logicService.increaseHeat(logic);
		request.setAttribute("logic", logic);
		return "/logic/logicEdit";
	}

	/**
	 * 修改logic
	 * 
	 * @param logic
	 * @return
	 */
	@RequestMapping("/edit")
	@ResponseBody
	public Json edit(Logic logic) {
		Json json = new Json();
		try {
			logicService.increaseHeat(logic);
			logicService.edit(logic);
			json.setSuccess(true);
			json.setMsg("修改成功！");
		} catch (Exception e) {
			logger.error("The error logic is : " + logic.toString());
			logger.error(e.getMessage(), e);
			json.setMsg("系统故障，请联系管理员");
		}
		return json;
	}

	/**
	 * 删除logic
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("/delete")
	@ResponseBody
	public Json delete(String id) {
		Json json = new Json();
		try {
			logicService.delete(id);
			json.setSuccess(true);
			json.setMsg("删除成功！");
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			json.setMsg("系统故障，请联系管理员");
		}
		return json;
	}

}
